<?php

namespace App\Providers;

use Dreamcat\ConfigClient\Api\NacosServerInterface;
use Dreamcat\ConfigClient\Consts\NacosConst;
use Dreamcat\ConfigClient\Impl\NacosConfigListener;
use Dreamcat\ConfigClient\Popo\NacosAppInfo;
use Illuminate\Support\ServiceProvider;

/**
 * -
 * @author vijay
 */
class NacosConfigListenerProvider extends ServiceProvider
{
    /** @inheritDoc */
    public function register()
    {
        $this->app
            ->bind(
                NacosConfigListener::class,
                function () {
                    return new NacosConfigListener(
                        $this->app->get(NacosServerInterface::class),
                        $this->getNacosListenAppInfo()
                    );
                }
            );
    }

    /**
     * @return NacosAppInfo[]
     */
    private function getNacosListenAppInfo(): array
    {
        $list = [];
        for ($idx = 1; ; ++$idx) {
            $dataId = env("NACOS_DATA_ID_{$idx}");
            if (!$dataId) {
                break;
            }
            $appInfo = new NacosAppInfo();
            $appInfo->setDataId($dataId)
                ->setGroup(env("NACOS_GROUP_{$idx}", NacosConst::DEFAULT_GROUP))
                ->setNamespaceName(env("NACOS_NAMESPACE_{$idx}", NacosConst::DEFAULT_NAMESPACE));
            $list[] = $appInfo;
        }
        return $list;
    }
}

# end of file
